/*
 * Copyright (C) 20015 MaiNaEr All rights reserved
 */
package com.bzchao.okhttpuploader;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.mainaer.wjoklib.okhttp.upload.UploadManager;
import com.mainaer.wjoklib.okhttp.upload.UploadTask;
import com.mainaer.wjoklib.okhttp.upload.UploadTaskListener;
import com.zhy.http.okhttp.callback.Callback;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * 类/接口描述
 *
 * @author wangjian
 * @date 2016/3/28.
 */
public class UpLoadActivity extends AppCompatActivity implements View.OnClickListener {
    private static String URL_Test_ID = "url_test";
    private UploadManager uploadManager;
    private ProgressBar mProgressBar;
    private Button mButtonStart;
    private Button mButtonPause;
    private Button mButtonCancel;
    private Button mButtonResume;
    private TextView mTvStatus;
    private String uploadApi = "http://192.168.101.7:8301/house-grade/upload";

    private String fileName = "5.mp4"; //保存文件名
    private String filePath; //文件储存路径

    UploadTaskListener uploadTaskListener = new UploadTaskListener() {
        @Override
        public void onUploading(UploadTask uploadTask, int position, int length) {
            double fen = (position * 1.0 / length) * 100;
            DecimalFormat df1 = new DecimalFormat("0.00");//0.00
            String format = df1.format(fen);
            mProgressBar.setProgress((int) fen);
            mTvStatus.setText("正在上传..." + format + "%");
        }

        @Override
        public void onUploadSuccess(UploadTask uploadTask, String filePath) {
            mTvStatus.setText("正在合并...：" + filePath);
            requestUnion(fileName);
        }

        @Override
        public void onError(UploadTask uploadTask, int errorCode, String msg) {
            mTvStatus.setText("上传失败" + errorCode + ":" + msg);
        }

        @Override
        public void onPause(UploadTask uploadTask) {
            mTvStatus.setText("上传暂停！");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);
        uploadManager = UploadManager.getInstance();
        initView();
    }

    private void initView() {
        //----------第一组下载----------------
        mProgressBar = findViewById(R.id.progressBar);
        mButtonStart = findViewById(R.id.button_start);
        mButtonStart.setOnClickListener(this);

        mButtonPause = findViewById(R.id.buttonpause);
        mButtonPause.setOnClickListener(this);

        mButtonCancel = findViewById(R.id.buttoncancel);
        mButtonCancel.setOnClickListener(this);

        mButtonResume = findViewById(R.id.buttonresume);
        mButtonResume.setOnClickListener(this);

        mTvStatus = findViewById(R.id.tv_status);
    }

    @Override
    public void onClick(View v) {
        if (mButtonStart == v) {
            filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + fileName;
            startUpload(fileName, filePath);
        } else if (mButtonPause == v) {
            uploadManager.pause(URL_Test_ID);
        } else if (mButtonResume == v) {
            uploadManager.resume(URL_Test_ID, uploadTaskListener);
        }
    }

    private void startUpload(String fileName, String filePath) {
        Map<String, String> params = new HashMap<>();
        params.put("filename", fileName);

        StringCallback callback = new StringCallback() {
            @Override
            public void onError(Call call, Exception e) {
                mTvStatus.setText("上传失败1：" + e.getLocalizedMessage());
            }

            @Override
            public void onResponse(String response) {
                Log.i("upload/check", response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    final int chunk = Integer.valueOf(jsonObject.getJSONObject("data").get("off").toString());
                    UploadTask task = new UploadTask()
                            .setId(URL_Test_ID)
                            .setUploadUrl(uploadApi + "/upload")
                            .setChunk(chunk)
                            .setFileName(fileName)
                            .setFilePath(filePath)
                            .setMListener(uploadTaskListener);
                    uploadManager.addUploadTask(task);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        //先检查文件，获取已上传的chunk数量
        OkHttpRequestUtils.getInstance(UpLoadActivity.this)
                .postFormData(uploadApi + "/check", params, callback);
    }

    private void requestUnion(String fileName) {
        Map<String, String> params = new HashMap<>();
        params.put("filename", fileName);
        //先检查文件，获取已上传的chunk数量
        Callback callback = new StringCallback() {
            @Override
            public void onError(Call call, Exception e) {
                mTvStatus.setText("上传失败2：" + e.getLocalizedMessage());
            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    mTvStatus.setText("上传完成：" + jsonObject.getJSONObject("data").get("msg").toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        OkHttpRequestUtils.getInstance(UpLoadActivity.this)
                .postFormData(uploadApi + "/union", params, callback);
    }

}
